<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class LoginController extends BaseController
{

    /**
     * 登錄
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function Login(Request $request)
    {

        $mobile = $request->input('mobile');
        $password = $request->input('password');

        $user = DB::table('users')->where('mobile', $mobile)->first();

        if (!$user) return $this->apiError('賬號密碼錯誤');
        if (!password_verify($password, $user->password)) return $this->apiError('賬號密碼錯誤!');

        $token=$this->CreateSaveToken($user->id);
       return $this->success(['token'=>$token]);

    }

    /**
     * 注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(RegisterRequest $request)
    {


       if( Redis::get($request->input('mobile')) !=$request->input('code')) return $this->apiError('验证码错误！');

        $data=  $request->except(['code']);
        $data['password']=bcrypt($data['password']);

        if(Users::create($data)) return $this->success();
        return $this->apiError('註冊失敗');
    }



    /**
     * 生成并保存token
     * @param array $arr
     * @return string
     */
    private function CreateSaveToken($arr =null)
    {
        // 生成token
        $token = sha1(md5(uniqid(md5(microtime(true)), true)));
//        $arr['token'] = $token;
        // 登录过期时间 604800 一周
       Redis::setex($token,604800,$arr);
        // 保存到缓存中

        // 返回token
        return $token;
    }

    /**
     * 忘记密码
     */
    public function forgetPassword(Request $request)
    {
       $res= Users::where('mobile',$request->input('mobile'))->first();
        if(!$res) return $this->apiError('該手機號未註冊');
        if( Redis::get($request->input('mobile')) !=$request->input('code')) return $this->apiError('验证码错误！');

        $data=  $request->except(['code']);
        $password=bcrypt($data['password']);
        Users::where('mobile',$request->input('mobile'))->update(['password'=>$password]);
        return $this->success();
    }

    /**
     * faceboook 登錄
     */
    public function appleFaceBookLogin(Request $request){
        $data['openid']= $request->post('openid');
        $data['avatarUrl']= $request->post('avatarUrl');
        $data['nickName']= $request->post('nickName');
        $data['clientId']= $request->post('clientId');
        $data['type']= $request->post('type');
         if(empty($data['openid']) || empty($data['clientId']) || empty($data['type']) || empty($data['nickName'])  ){
            return $this->apiError('參數不能為空');
        }else{
            $user = Users::where('facebook_id',$data['openid'])->first();
            $User = new Users();
            if(empty($user)){
                try{
                    DB::beginTransaction();
                    
                    $User->username = $data['nickName'];
                    $User->client_id = $data['clientId'];
                    $User->type = $data['type'];
                    $User->facebook_id = $data['openid'];
                    $User->head_pic =  $data['avatarUrl'];
                    $User->password = bcrypt('123456');
                    if($User->save()){
                        $token = $this->CreateSaveToken($User->id);
                         DB::commit();
                         return $this->success(['token' =>$token]);
                    }else{
                         DB::rollBack();
                         return $this->error("Error");
                     }
                 }catch (\Exception $e){
                    DB::rollBack();
                    return $this->error($e->getMessage());
                 }
             }else{
                // if (Auth::attempt(['email' => $user['email'], 'password' => '123456','facebook_id' => $user['facebook_id']])) {
                //         $USERS = Auth::user();
                //         $token = $USERS->createToken($user['id'])->accessToken;
                //         $updateInfo = User::where('id', $user['id'])->update(['tokenType' => $data['tokenType'], 'client_id' => $data['clientId']]);
                //         if($updateInfo){
                //             return $this->success(['token' =>$token]);
                //         }else{
                //             return $this->error('Error!');
                //         }
                //     }else{
                //         return $this->error('Error!!');
                //     }
                    
                    $token = $this->CreateSaveToken($user->id);
                    return $this->success(['token' =>$token]);
                }
        }
    }

    public function appleLogin(Request $request){

       
        $data['openid']= $request->post('openid');
        
        $Name=$request->post('nickName');
        $data['nickName']= empty($Name) ? '手機用戶'.time().rand(1000,9999) : $Name['familyName'].$Name['giveName'];
        //  $data['nickName']=  'IOS手機用戶'.time().rand(1000,9999) ;
        $data['clientId']= $request->post('clientId');
        $data['type']= $request->post('type');
        
         if(empty($data['openid']) || empty($data['clientId']) || empty($data['type'])   ){
            return $this->apiError('參數不能為空');
        }else{
            $user = Users::where('apple_id',$data['openid'])->first();
            $User = new Users();
            if(empty($user)){
                try{
                    DB::beginTransaction();
                    
                    $User->username = $data['nickName'];
                    $User->client_id = $data['clientId'];
                    $User->type = $data['type'];
                    $User->apple_id = $data['openid'];
                    // $User->head_pic =  $data['avatarUrl'];
                    $User->password = bcrypt('123456');
                    if($User->save()){
                        $token = $this->CreateSaveToken($User->id);
                         DB::commit();
                         return $this->success(['token' =>$token]);
                    }else{
                         DB::rollBack();
                         return $this->apiError("Error");
                     }
                 }catch (\Exception $e){
                    DB::rollBack();
                    return $this->error($e->getMessage());
                 }
             }else{
                // if (Auth::attempt(['email' => $user['email'], 'password' => '123456','facebook_id' => $user['facebook_id']])) {
                //         $USERS = Auth::user();
                //         $token = $USERS->createToken($user['id'])->accessToken;
                //         $updateInfo = User::where('id', $user['id'])->update(['tokenType' => $data['tokenType'], 'client_id' => $data['clientId']]);
                //         if($updateInfo){
                //             return $this->success(['token' =>$token]);
                //         }else{
                //             return $this->error('Error!');
                //         }
                //     }else{
                //         return $this->error('Error!!');
                //     }
                    
                    $token = $this->CreateSaveToken($user->id);
                    return $this->success(['token' =>$token]);
                }
        }
    }
}
